package servlet;

import model.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@WebServlet("/new-company")
public class 新发布招聘信息 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        Ruser currentUser = (Ruser) session.getAttribute("rcurrentUser");
        Integer ruid = currentUser.ruid;
        PrintWriter out = resp.getWriter();
        if (ruid == null) {
            out.print("<script language='javascript'>alert('Wrong password. Login again!!'");
            return;
        }
        String gtitle = req.getParameter("gtitle");
        String gtype = req.getParameter("gtype");
        String gsalary = req.getParameter("gsalary");
        String gcontents = req.getParameter("gcontents");
        String address = req.getParameter("address");
        String twoAddress = req.getParameter("two-address");
        String lastAddress = address+"-"+twoAddress;
        LocalDate date = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyy-MM-dd");
        String day = date.format(formatter);
        System.out.println(currentUser.ruid);
        System.out.println(gtitle);
        System.out.println(gtype);
        System.out.println(gsalary);
        System.out.println(gcontents);
        Company company;
        try {
            company = sava(ruid, gtitle, gtype, gsalary, gcontents,lastAddress,day);
            resp.sendRedirect("/");
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }

    }

    public static Company sava(Integer ruid, String gtitle, String gtype, String gsalary, String gcontents,String lastAddress,String day) throws SQLException {
        try (Connection c = DBUtil.getConnection()) {
            String sql = "INSERT INTO company(ruid,gtitle,gtype,gsalary,gcontents,address,day) VALUES(?,?,?,?,?,?,?)";
            try (PreparedStatement s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                s.setInt(1, ruid);
                s.setString(2, gtitle);
                s.setString(3, gtype);
                s.setString(4, gsalary);
                s.setString(5, gcontents);
                s.setString(6,lastAddress);
                s.setString(7,day);
                s.executeUpdate();

            }
        }
        return null;
    }
}


